package cn.edu.fzu.homemaking.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

import javax.annotation.Resource;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.fzu.homemaking.api.CompanyApi;
import cn.edu.fzu.homemaking.cache.AreaCache;
import cn.edu.fzu.homemaking.domain.dto.AssignLabels;
import cn.edu.fzu.homemaking.domain.dto.SysCompanyDTO;
import cn.edu.fzu.homemaking.domain.entity.SysCompany;
import cn.edu.fzu.homemaking.domain.enums.StatusEnum;
import cn.edu.fzu.homemaking.domain.vo.CountCompany;
import cn.edu.fzu.homemaking.exception.ServiceException;
import cn.edu.fzu.homemaking.mapper.SysCompanyMapper;
import cn.edu.fzu.homemaking.service.SysCompanyService;
import cn.edu.fzu.homemaking.util.ExceptionUtil;
import cn.edu.fzu.homemaking.web.RetCode;

/**
 * @author yifan
 * @date 2023/4/4
 */
@Service
@Transactional
public class SysCompanyServiceImpl implements SysCompanyService {

    @Resource
    private SysCompanyMapper sysCompanyMapper;

    @Resource
    private AreaCache        areaCache;

    @Resource
    private CompanyApi       companyApi;

    @Override
    public List<SysCompany> list(String name, String creditCode, String legalPerson, String businessLicense,
                                 String contact, String phone, StatusEnum status, Long areaId, Long cityId,
                                 Long provinceId, Long labelId) {

        // 分析出areaId
        List<Long> areaIdList = null;
        if (areaId != null) {
            areaIdList = Collections.singletonList(areaId);
        } else if (cityId != null) {
            areaIdList = areaCache.getAreaIdsByCityId(cityId);
        } else if (provinceId != null) {
            areaIdList = areaCache.getAreaIdsByProvinceId(provinceId);
        }

        List<SysCompany> companies = sysCompanyMapper.list(name, creditCode, legalPerson, businessLicense, contact,
                phone, status, areaIdList, labelId);
        return companies;
    }


    @Override
    public void addCompany(String name, String creditCode, String legalPerson, String businessLicense, String contact,
                           String phone, Long areaId, String address) {
        try {
            sysCompanyMapper.insertCompany(name, creditCode, legalPerson, businessLicense, contact, phone,
                    StatusEnum.NORMAL, areaId, address);
        } catch (DuplicateKeyException e) {
            throw new ServiceException(RetCode.RESUSE_OPERATOR, "添加公司失败：信用代码已存在");
        } catch (Exception e) {
            String errorMsg = ExceptionUtil.getErrorMsg(e);
            // 这也是主键冲突异常
            if (errorMsg.contains("Duplicate entry")) {
                throw new ServiceException(RetCode.RESUSE_OPERATOR, "添加公司失败：信用代码已存在");
            }
        }
    }


    @Override
    public void assignLabels(AssignLabels assignLabels) {
        sysCompanyMapper.assignLabels(assignLabels.getCompanyId(), assignLabels.getLabelIds());
    }


    @Override
    public void removeLabels(AssignLabels assignLabels) {
        Boolean removable = false;
        if (removable) {
            throw new ServiceException(RetCode.RESUSE_OPERATOR, "移除失败：有服务绑定了待移除标签");
        }

        sysCompanyMapper.removeLabels(assignLabels.getCompanyId(), assignLabels.getLabelIds());
    }


    @Override
    public void updateCompany(Long id, String name, String creditCode, String legalPerson, String businessLicense,
                              String contact, String phone, StatusEnum status, Long areaId, String address) {
        sysCompanyMapper.update(id, name, creditCode, legalPerson, businessLicense, contact, phone, status, areaId, address);
    }


    @Override
    public void assignLabel(Long companyId, Long labelId) {
        sysCompanyMapper.assignLabel(companyId, labelId);
    }


    @Override
    public void removeLabel(Long companyId, Long labelId) {
        int serviceCnt = sysCompanyMapper.countService(companyId, labelId);
        if (serviceCnt > 0) {
            throw new ServiceException(RetCode.RESUSE_OPERATOR, "待移除标签下存在服务");
        }
        sysCompanyMapper.removeLabel(companyId, labelId);
    }


    @Override
    public SysCompanyDTO getById(Long id) {
        return sysCompanyMapper.getById(id);
    }


    @Override
    public CountCompany countCompany() {
        CountCompany countCompany = new CountCompany();
        List<SysCompanyDTO> companies = sysCompanyMapper.listForCount();
        countCompany.setTotal((long) companies.size());
        Stream<SysCompanyDTO> activeCompanies = companies.stream()
                .filter(sysCompany -> sysCompany.getStatus() == StatusEnum.NORMAL);
        countCompany.setActive(activeCompanies.count());
        return countCompany;
    }
}
